function utf16to8(str) {
	var out, i, len, c;
	out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
		c = str.charCodeAt(i);
		if ((c >= 0x0001) && (c <= 0x007F)) {
		    out += str.charAt(i);
		} else if (c > 0x07FF) {
		    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
		    out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
		    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
		} else {
		    out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
		    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
		}
    }
    return out;
}

function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
    
function base64encode(str) {
    var out, i, len;
    var c1, c2, c3;
    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
		 c1 = str.charCodeAt(i++) & 0xff;
		 if(i == len)
		 {
		     out += base64EncodeChars.charAt(c1 >> 2);
		     out += base64EncodeChars.charAt((c1 & 0x3) << 4);
		     out += "==";
		     break;
		 }
		 c2 = str.charCodeAt(i++);
		 if(i == len)
		 {
		     out += base64EncodeChars.charAt(c1 >> 2);
		     out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
		     out += base64EncodeChars.charAt((c2 & 0xF) << 2);
		     out += "=";
		     break;
		 }
		 c3 = str.charCodeAt(i++);
		 out += base64EncodeChars.charAt(c1 >> 2);
		 out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
		 out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
		 out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}

function base64decode(str) {
    var c1, c2, c3, c4;
    var i, len, out;
    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
	 /* c1 */
	 do {
	     c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
	 } while(i < len && c1 == -1);
	 if(c1 == -1)
	     break;
	 /* c2 */
	 do {
	     c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
	 } while(i < len && c2 == -1);
	 if(c2 == -1)
	     break;
	 out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
	 /* c3 */
	 do {
	     c3 = str.charCodeAt(i++) & 0xff;
	     if(c3 == 61)
	  return out;
	     c3 = base64DecodeChars[c3];
	 } while(i < len && c3 == -1);
	 if(c3 == -1)
	     break;
	 out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
	 /* c4 */
	 do {
	     c4 = str.charCodeAt(i++) & 0xff;
	     if(c4 == 61)
	  return out;
	     c4 = base64DecodeChars[c4];
	 } while(i < len && c4 == -1);
	 if(c4 == -1)
	     break;
	 out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
}

new_single_class = function(F) {
    var C = function(){}
    C.prototype = F;
    return new C;
};
	
function escapeHTML(str) {  
  str = String(str).replace(/&/g, '&amp;').  
    replace(/>/g, '&gt;').  
    replace(/</g, '&lt;').  
    replace(/"/g, '&quot;');  
  return str;  
}  
function unescapeHTML(str) {  
  str = String(str).replace(/&gt;/g, '>').  
    replace(/&lt;/g, '<').  
    replace(/&quot;/g, '"').  
    replace(/&amp;/g, '&');  
  return str;  
}  

String.format = function() {
    if( arguments.length == 0 )
        return null;

    var str = arguments[0]; 
    for(var i=1;i<arguments.length;i++) {
        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

if(!Array.indexOf) {
    Array.prototype.indexOf = function(obj) 
    {                
        for(var i=0; i<this.length; i++) 
        { 
            if(this[i]==obj) 
            { 
                return i; 
            } 
        } 
        return -1; 
    } 
}

//if(!Array.contains){
//    Array.prototype.contains = function(obj) {
//        var i = this.length;
//        while (i--) {
//            if (this[i] === obj) {
//                return true;
//            }
//        }
//        return false;
//    }
//}


function make_name_string(str){
	return "'" + str + "'"
}

function latecallfun1(a,func){
	s = function() {
		func(a)
	}
	return s
}

function latecallfun2(a,b,func){
	s = function() {
		func(a,b)
	}
	return s
}

function latecallfun3(a,b,c,func){
	s = function() {
		func(a,b,c)
	}
	return s
}

function latecallfun4(a,b,c,d,func){
	s = function() {
		func(a,b,c,d)
	}
	return s
}

function latecallfun5(a,b,c,d,e,func){
	s = function() {
		func(a,b,c,d,e)
	}
	return s
}

function latecallfun6(a,b,c,d,e,f,func){
	s = function() {
		func(a,b,c,d,e,f)
	}
	return s
}

function latecallfun7(a,b,c,d,e,f,g,func){
	s = function() {
		func(a,b,c,d,e,f,g)
	}
	return s
}

function latecallfun8(a,b,c,d,e,f,g,h,func){
	s = function() {
		func(a,b,c,d,e,f,g,h)
	}
	return s
}

//第一个参数需要后输入
function latecall_wp1_fun1(func){
	s = function(a) {
		func(a)
	}
	return s
}

function latecall_wp1_fun2(b,func){
	s = function(a) {
		func(a,b)
	}
	return s
}

function latecall_wp1_fun3(b,c,func){
	s = function(a) {
		func(a,b,c)
	}
	return s
}

function latecall_wp1_fun4(b,c,d,func){
	s = function(a) {
		func(a,b,c,d)
	}
	return s
}

function latecall_wp1_fun5(b,c,d,e,func){
	s = function(a) {
		func(a,b,c,d,e)
	}
	return s
}

function latecall_wp1_fun6(b,c,d,e,f,func){
	s = function(a) {
		func(a,b,c,d,e,f)
	}
	return s
}

function latecall_wp1_fun7(b,c,d,e,f,g,func){
	s = function(a) {
		func(a,b,c,d,e,f,g)
	}
	return s
}

function latecall_wp1_fun8(b,c,d,e,f,g,h,func){
	s = function(a) {
		func(a,b,c,d,e,f,g,h)
	}
	return s
}

//第二个参数需要输入
function latecall_wp2_fun2(a,func){
    s = function(b) {
        func(a,b)
    }
    return s
}

//第三个参数需要输入
function latecall_wp3_fun2(a, b,func){
    s = function(c) {
        func(a,b, c)
    }
    return s
}

function input_params_to_json(str_input){
    var obj = {}
    var words = str_input.split(',')
    for(var w in words){
        var kv = words[w].split('=')
        obj[kv[0]] = kv[1]
    }
    return obj
}

function getUrlValue(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

function updateUrlValue(url, name, value, replace_exist){
    var r = url;
    if (r != null && r != 'undefined' && r != "") {
        value = encodeURIComponent(value);
        var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
        var tmp = name + "=" + value;
        if (url.match(reg) != null) {
            if(replace_exist){
                r = url.replace(eval(reg), tmp);
            }
        }
        else {
            if (url.match("[\?]")) {
                r = url + "&" + tmp;
            } else {
                r = url + "?" + tmp;
            }
        }
    }
    return r;
}

function changeURLPar(destiny, par, par_value)
{
    var pattern = par+'=([^&]*)';
    var replaceText = par+'='+par_value;
    if (destiny.match(pattern))
    {
        var tmp = '/\\'+par+'=[^&]*/';
        tmp = destiny.replace(eval(tmp), replaceText);
        return (tmp);
    }
    else
    {
        if (destiny.match('[\?]'))
        {
            return destiny+'&'+ replaceText;
        }
        else
        {
            return destiny+'?'+replaceText;
        }
    }
    return destiny+'\n'+par+'\n'+par_value;
}

function splitUrl(sURL){
    var urlLink = sURL;
    var urlParams = {};
    if (sURL.indexOf("?") > 0)
    {
        //分解URL,第二的元素为完整的查询字符串
        //即arrayParams[1]的值为【id=1&action=2】
        var arrayParams = sURL.split("?");
        urlLink = arrayParams[0]
        //分解查询字符串
        //arrayURLParams[0]的值为【id=1 】
        //arrayURLParams[2]的值为【action=add】
        var arrayURLParams = arrayParams[1].split("&");
        //遍历分解后的键值对
        for (var i = 0; i < arrayURLParams.length; i++)
        {
            //分解一个键值对
            var sParam = arrayURLParams[i].split("=");
            urlParams[sParam[0]] = decodeURIComponent(sParam[1])
        }
    }
    return [urlLink,urlParams];
}

function get_htmlelemet_by_id(id) {
     return document.getElementById(id);
}

function get_screen_width(){
	return window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth
}

function get_screen_height(){
	return window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight
}

var error_check = function(data, status){
	return true;
}

function get_server_info_text(url, param, funccallback){
	$.get(url, param, function(data,status){funccallback(data)},'text')
}

function get_server_info_json(url, param, funccallback){
	$.get(url, param, function(data,status){funccallback(data)}, 'json')
}

function post_server_info_json(url, param, funccallback){
	$.post(url, param, function(data,status){funccallback(data)}, 'json')
}

function _text(url, param, funcsuccess, funcfail){
	var dd={params:JSON.stringify(param)};
	$.get(url, dd, function(data,status){
		//alert(url)		alert(status)		alert(data)
		if(error_check(data,status)){
			if(funcsuccess) {funcsuccess(data)}
		} else{
			if(funcfail){funcfail(data)}
		}
	},'text')
}
function _html(url, params, callback){
    $.ajax(url, {
        'type':'get',
        'data': params,
        'contentType':'application/json',
        'dataType':'text',
        'success':callback
    })
}

function _json_ajax(url, param, funcsuccess, funcfail){
    var dd=JSON.stringify(param);
    $.ajax(url, {
        'type':'post',
        'data': dd,
        'contentType':'application/json',
        'dataType':'json',
        'success':function(data,status) {
            //alert(url)		alert(status)		alert(data)
            if (error_check(data, status)) {
                if (funcsuccess) funcsuccess(data)
            } else if (funcfail) {
                if (funcfail) funcfail(data)
            }
        },
        fail:funcfail
    })
}

function _json(url, param, funcsuccess, funcfail){
	var dd=JSON.stringify(param);
    console.log(dd);
	$.post(url, dd, function(data,status){
		//alert(url)		alert(status)		alert(data)
		if(error_check(data,status)){
			if(funcsuccess) funcsuccess(data)
		} else if(funcfail){
			if(funcfail) funcfail(data)
		}
	}, 'json').fail(funcfail)
}

function _json_get(url, param, funcsuccess, funcfail){
    $.get(url, param, function(data,status){
        //alert(url)		alert(status)		alert(data)
        if(error_check(data,status)){
            if(funcsuccess) funcsuccess(data)
        } else if(funcfail){
            if(funcfail) funcfail(data)
        }
    }, 'json').fail(funcfail)
}

function _json_f(url, param, funcsuccess, funcfail){
	var dd={params:JSON.stringify(param)};
	$.post(url, dd, function(data,status){
		//alert(url)		alert(status)		alert(data)
		if(error_check(data,status)){
			if(funcsuccess) funcsuccess(data)
		} else if(funcfail){
			if(funcfail) funcfail(data)
		}
	}, 'json').fail(funcfail)
}

function _form(url, param, funcsuccess, funcfail){
	$.post(url, param, function(data,status){
		//alert(url)		alert(status)		alert(data)
		if(error_check(data,status)){
			if(funcsuccess) funcsuccess(data)
		} else if(funcfail){
			if(funcfail) funcfail(data)
		}
	}, 'json').fail(funcfail)
}

function _form_get(url, param, funcsuccess, funcfail){
    $.get(url, param, function(data,status){
        //alert(url)		alert(status)		alert(data)
        if(error_check(data,status)){
            if(funcsuccess) funcsuccess(data)
        } else if(funcfail){
            if(funcfail) funcfail(data)
        }
    }, 'json').fail(funcfail)
}

function _form_cors(url, param, success, error){
    $.ajax(url, {
        'type':'post',
        'data': param,
        'contentType':'application/x-www-form-urlencoded',
        'dataType':'json',
        'success':success,
        'error':error,
        //'withCredentials':true,
        xhrFields:{
			withCredentials:true
        },
		crossDomain:true
    })
}

function _form_cors_no_cookies(url, param, success, error){
    $.ajax(url, {
        'type':'post',
        'data': param,
        'contentType':'application/x-www-form-urlencoded',
        'dataType':'json',
        'success':success,
        'error':error,
		crossDomain:true
    })
}


function _json_f_cors(url, param, success, error){
	var dd={params:JSON.stringify(param)};
    $.ajax(url, {
        'type':'post',
        'data': dd,
        'contentType':'application/x-www-form-urlencoded',
        'dataType':'json',
        'success':success,
        'error':error,
        //'withCredentials':true
        xhrFields:{
			withCredentials:true
		},
		crossDomain:true
    })
}

function _json_cors(url, param, success, error){
	var dd=JSON.stringify(param);
    $.ajax(url, {
        'type':'post',
        'data': dd,
        'contentType':'application/json',
        'dataType':'json',
        'success':success,
        'error':error,
        //'withCredentials':true
        xhrFields:{
			withCredentials:true
		},
		crossDomain:true
    })
}

function _file_cors(url, name, file_element_selector, success, fail){
    var data = new FormData();
    data.append('file', $(file_element_selector)[0].files[0]);
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType:'json',
        processData: false,
        contentType: false,
        xhrFields:{
			withCredentials:true
		},
		crossDomain:true
    }).done(function(ret){
        if (ret) {
            if(success){success(ret)}
        }else{
            if(fail){fail()}
        }
    });
}

function _file(url, name, file_element_selector, success, fail){
    var data = new FormData();
    data.append(name, $(file_element_selector)[0].files[0]);
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType:'json',
        processData: false,
        contentType: false
    }).done(function(ret){
        if (ret) {
            if(success){success(ret)}
        }else{
            if(fail){fail()}
        }
    });
}

function _file_direct(url, name, file, success, fail){
    var data = new FormData();
    data.append(name, file);
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType:'json',
        processData: false,
        contentType: false
    }).done(function(ret){
        if (ret) {
            if(success){success(ret)}
        }else{
            if(fail){fail()}
        }
    });
}

function query_json_and_exec_func(url, param, processFunc){
	$.get(url, param, function(data){processFunc(data)}, 'json')
}

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
}

if($.browser){}else{$.browser={}}
$.browser.msie = isMobile.Windows()

$.extend({
     writeLinkFile:function(includePath,file) {
        var files = typeof file == "string" ? [file]:file;
        for (var i = 0; i < files.length; i++) {
            var name = files[i].replace(/^s|s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + includePath + name + "'";
            if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
        }
   },

	addLinkFile: function(filename){
        if(filename && filename.length>0){
        }else{
            return;
        }
        var name = filename;
        var att = name.split('.');
        var ext = att[att.length - 1].toLowerCase();
        var isCSS = ext == "css";
        var isJs = ext == "js";
        if (isJs)
        {
            var fileref=document.createElement('script')//创建标签
            fileref.setAttribute("type","text/javascript")//定义属性type的值为text/javascript
            fileref.setAttribute("src", filename)//文件的地址
        }
        else if (isCSS)
        {
            var fileref=document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        if (typeof fileref!="undefined")  {
            document.getElementsByTagName("head")[0].appendChild(fileref)
        }
    },


    loadJsCssS:function(file){
        var files = typeof file == "string" ? [file] : file
        for (var i = 0; i < files.length; i++) {
            $.addLinkFile(file)
        }
    },

	reloadjs:function(jsname){
		$('script[src*="' + jsname + '"]').attr('src', $('script[src*="' + jsname + '"]').attr('src') +'&'+new Date().getTime());
	},

	insertJSToContent: function (sId, source)
    {
        if ( ( source != null )/* && ( !document.getElement( sId ) )*/ ){
            var oHead = document.getElementsByTagName('HEAD').item(0);
            var oScript = document.createElement( "script" );
            oScript.language = "javascript";
            oScript.type = "text/javascript";
            oScript.id = sId;
            oScript.defer = true;
            oScript.text = source;
            oHead.appendChild( oScript );
        }
    },

    createScriptContent: function (sId, source)
    {
        if ( ( source != null )/* && ( !document.getElement( sId ) )*/ ){
            var oScript = document.createElement( "script" );
            oScript.language = "javascript";
            oScript.type = "text/javascript";
            oScript.id = sId;
            oScript.defer = true;
            oScript.text = source;
            return oScript
        }else{
            return null;
        }
    },

    reloadByScriptTypes : function(scriptType, element){
        $("script[type='"+scriptType+"']").each(function(i,scriptC){
            var scriptContent = $(scriptC).text();
            var scriptId = $(scriptC).data("sid")
            if(element){
                var se = $.createScriptContent(scriptId, scriptContent)
                $(element).append(se)
            }else{
                $.insertJSToContent(scriptId, scriptContent)
            }

        })
    },

    loadJSToContent: function (sId, url, parentItemId)
    {
        if ( ( url != null )/* && ( !document.getElement( sId ) )*/ ){
            _text(url, null, function(source){
                var scriptContent =  source
                var element = null;
                if(parentItemId){
                    element = '#'+parentItemId
                }
                if (element){
                    var se = $.createScriptContent(sId, scriptContent)
                    $(element).append(se)
                }else{
                    $.insertJSToContent(sId, scriptContent)
                }
            })
        }
    },

    loadJSToElement: function (sId, url, element)
    {
        if ( ( url != null )/* && ( !document.getElement( sId ) )*/ ){
            _text(url, null, function(source){
                var scriptContent =  source
                if (element){
                    var se = $.createScriptContent(sId, scriptContent)
                    $(element).append(se)
                }else{
                    $.insertJSToContent(sId, scriptContent)
                }
            })
        }
    },

    loadJsCss: function(filename, elementid){
        if(filename && filename.length>0){
        }else{
            return;
        }
        var name = filename;
        var att = name.split('.');
        var ext = att[att.length - 1].toLowerCase();
        var isCSS = (ext.indexOf("css")>=0);
        var isJs = (ext.indexOf("js")>=0);
        if (isJs)
        {
            var fileref=document.createElement('script')//创建标签
            fileref.setAttribute("type","text/javascript")//定义属性type的值为text/javascript
            fileref.setAttribute("src", filename)//文件的地址
        }
        else if (isCSS)
        {
            var fileref=document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        if (typeof fileref!="undefined")  {
            if(elementid){
                document.getElementById(elementid).appendChild(fileref)
            }else{
                document.getElementsByTagName("head")[0].appendChild(fileref)
            }
        }
    }
});
